package pt.ipp.estgf.countrylistexample_db;

import java.util.ArrayList;
import java.util.List;



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MyDbHelper extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "mydatabase.db";
	private static final int DATABASE_VERSION = 2;
	private Context context;

	public MyDbHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
		this.context = context;
		Log.d("TAG", "CRIAR MYDBHELPER");

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		Log.d("TAG", "em oncreateHelper");

		db.execSQL("CREATE TABLE Country (id INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ "name VARCHAR(50) NOT NULL, continent VARCHAR(50) NOT NULL)");
		addContry(db, new Country("Portugal", "Europa"));
		addContry(db, new Country("Brazil", "America"));
		addContry(db, new Country("Espanha", "Europa"));
		addContry(db, new Country("Italia", "Europa"));
		addContry(db, new Country("Franca", "Europa"));
		addContry(db, new Country("Alemanha", "Europa"));
		Log.d("TAG", "A CRIAR DB");
		
	}

	public boolean addContry(SQLiteDatabase db, Country country) {

		ContentValues values = new ContentValues();
		values.put("name", country.getName());
		values.put("continent", country.getContinent());
		db.insert("Country", null, values);

		return true;
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

		db.execSQL("DROP TABLE Country");
		this.onCreate(db);

	}

	public List<Country> getCountrys(SQLiteDatabase db,
		List<Country> countryList, String continent) {
		
		countryList.clear();
		Cursor cursor;
		if (continent==null) {
			cursor = db.rawQuery("SELECT * FROM Country", null);
		} else {
			cursor = db.rawQuery("SELECT * FROM Country WHERE continent LIKE \"%"
					+ continent + "%\"", null);
		}
		if (cursor != null && cursor.moveToFirst()) {
			do {
				countryList.add(new Country(cursor.getInt(0), cursor.getString(1),cursor
						.getString(2)));
			} while (cursor.moveToNext());
		}
		cursor.close();
		return countryList;
	}
	
	public boolean removeCountry(SQLiteDatabase db,int id){
		
		db=this.getWritableDatabase();
		db.execSQL("DELETE FROM Country WHERE id="+id);
		return true;
	}
}
